package cn.edu.scujcc;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
	@Autowired
	private UserRepository repo;
	
	public User createUser(User u) {
		User result = null;
		result = repo.save(u);
		return result;
	}

	public User updateUser(User u) {
		User result = null;
		result = getUser(u.getSd());
		if (result != null) {
			if (u.getName() != null) {
				result.setName(u.getName());
			}
			if (u.getGender() != null) {
				result.setGender(u.getGender());
			}
			if (u.getAge() != null) {
				result.setAge(u.getAge());
			}
			if (u.getPortail() != null) {
				result.setPortail(u.getPortail());
			}
			if (u.getSection() != null) {
				result.setSection(u.getSection());
			}
			if (u.getIDcard() != null) {
				result.setIDcard(u.getIDcard());
			}
			result = repo.save(result);
		}
		
		return result;
	}

	public List<User> getAllUser() {
		List<User> result = null;
		result = repo.findAll();
		return result;
	}
	
	public User getUser(String sd) {
		User result = null;
		Optional<User> op = repo.findById(sd);
		if (op.isPresent()) {
			result = op.get();
		}
		return result;
	}
	
	public boolean deleteUser(String sd) {
		boolean result = true;
		try {
			repo.deleteById(sd);
		} catch (Exception u) {
			result = false;
		}
		return result;
	}
	
	public List<User> searchUser(String section){
		List<User> result = null;
		result = repo.findBySection(section);
		return result;
	}

}
